package com.itheima.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @Author：shenkunlin
 * @date： 2021/7/12 16:08
 * @Description：全局过滤器
 ***/
@Configuration
public class LoginGlobalFilter implements GlobalFilter, Ordered {
    /**
     * 拦截
     * @param exchange
     * @param chain
     *  Mono<Void>:返回信息的封装
     *  ServerWebExchange:上下文对象
     *  GatewayFilterChain:执行链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("------------------鉴权------------------");
        //获取request和response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //获取用户身份信息->【用户每次请求，会把身份信息封装到请求头中 token】
        String token = request.getHeaders().getFirst("token");

        //if(StringUtils.isEmpty(token)){
        //    //如果请求头没有用户身份信息，响应用户->无权访问->401
        //    //设置状态码
        //    response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //    //消息设置
        //    return response.writeWith(Flux.just(response.bufferFactory().wrap("请您先登录！".getBytes())));
        //}

        //执行下一个链路
        return chain.filter(exchange);
    }

    /**
     * 执行顺序，多个拦截器执行是有顺序的
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
